home *** CD-ROM | disk | FTP | other *** search
/ Aminet 40 / Aminet 40 (2000)(Schatztruhe)[!][Dec 2000].iso / Aminet / dev / lang / Python16_Src.lha / Python16_Source / Objects / fileobject.c < prev    next >
Encoding:
C/C++ Source or Header  |  2000-09-10  |  23.7 KB  |  1,171 lines

  1. /* File object implementation */
  2.  
  3. #include "Python.h"
  4. #include "structmember.h"
  5.  
  6. #ifndef DONT_HAVE_SYS_TYPES_H
  7. #include <sys/types.h>
  8. #endif /* DONT_HAVE_SYS_TYPES_H */
  9.  
  10. #ifdef HAVE_UNISTD_H
  11. #include <unistd.h>
  12. #endif
  13.  
  14. #ifdef MS_WIN32
  15. #define ftruncate _chsize
  16. #define fileno _fileno
  17. #define HAVE_FTRUNCATE
  18. #endif
  19.  
  20. #ifdef macintosh
  21. #ifdef USE_GUSI
  22. #define HAVE_FTRUNCATE
  23. #endif
  24. #endif
  25.  
  26. #ifdef THINK_C
  27. #define HAVE_FOPENRF
  28. #endif
  29. #ifdef __MWERKS__
  30. /* Mwerks fopen() doesn't always set errno */
  31. #define NO_FOPEN_ERRNO
  32. #endif
  33.  
  34. #define BUF(v) PyString_AS_STRING((PyStringObject *)v)
  35.  
  36. #ifndef DONT_HAVE_ERRNO_H
  37. #include <errno.h>
  38. #endif
  39.  
  40. typedef struct {
  41.     PyObject_HEAD
  42.     FILE *f_fp;
  43.     PyObject *f_name;
  44.     PyObject *f_mode;
  45.     int (*f_close) Py_PROTO((FILE *));
  46.     int f_softspace; /* Flag used by 'print' command */
  47.     int f_binary; /* Flag which indicates whether the file is open
  48.              open in binary (1) or test (0) mode */
  49. } PyFileObject;
  50.  
  51. #include "protos/fileobject.h"
  52.  
  53. FILE *
  54. PyFile_AsFile(f)
  55.     PyObject *f;
  56. {
  57.     if (f == NULL || !PyFile_Check(f))
  58.         return NULL;
  59.     else
  60.         return ((PyFileObject *)f)->f_fp;
  61. }
  62.  
  63. PyObject *
  64. PyFile_Name(f)
  65.     PyObject *f;
  66. {
  67.     if (f == NULL || !PyFile_Check(f))
  68.         return NULL;
  69.     else
  70.         return ((PyFileObject *)f)->f_name;
  71. }
  72.  
  73. PyObject *
  74. PyFile_FromFile(fp, name, mode, close)
  75.     FILE *fp;
  76.     char *name;
  77.     char *mode;
  78.     int (*close) Py_FPROTO((FILE *));
  79. {
  80.     PyFileObject *f = PyObject_NEW(PyFileObject, &PyFile_Type);
  81.     if (f == NULL)
  82.         return NULL;
  83.     f->f_fp = NULL;
  84.     f->f_name = PyString_FromString(name);
  85.     f->f_mode = PyString_FromString(mode);
  86.     f->f_close = close;
  87.     f->f_softspace = 0;
  88.     if (strchr(mode,'b') != NULL)
  89.         f->f_binary = 1;
  90.     else
  91.         f->f_binary = 0;
  92.     if (f->f_name == NULL || f->f_mode == NULL) {
  93.         Py_DECREF(f);
  94.         return NULL;
  95.     }
  96.     f->f_fp = fp;
  97.     return (PyObject *) f;
  98. }
  99.  
  100. PyObject *
  101. PyFile_FromString(name, mode)
  102.     char *name, *mode;
  103. {
  104.     extern int fclose Py_PROTO((FILE *));
  105.     PyFileObject *f;
  106.     f = (PyFileObject *) PyFile_FromFile((FILE *)NULL, name, mode, fclose);
  107.     if (f == NULL)
  108.         return NULL;
  109. #ifdef HAVE_FOPENRF
  110.     if (*mode == '*') {
  111.         FILE *fopenRF();
  112.         f->f_fp = fopenRF(name, mode+1);
  113.     }
  114.     else
  115. #endif
  116.     {
  117.         Py_BEGIN_ALLOW_THREADS
  118.         f->f_fp = fopen(name, mode);
  119.         Py_END_ALLOW_THREADS
  120.     }
  121.     if (f->f_fp == NULL) {
  122. #ifdef NO_FOPEN_ERRNO
  123.         /* Metroworks only, not testable, so unchanged */
  124.         if ( errno == 0 ) {
  125.             PyErr_SetString(PyExc_IOError, "Cannot open file");
  126.             Py_DECREF(f);
  127.             return NULL;
  128.         }
  129. #endif
  130.         PyErr_SetFromErrnoWithFilename(PyExc_IOError, name);
  131.         Py_DECREF(f);
  132.         return NULL;
  133.     }
  134.     return (PyObject *)f;
  135. }
  136.  
  137. void
  138. PyFile_SetBufSize(f, bufsize)
  139.     PyObject *f;
  140.     int bufsize;
  141. {
  142.     if (bufsize >= 0) {
  143. #ifdef HAVE_SETVBUF
  144.         int type;
  145.         switch (bufsize) {
  146.         case 0:
  147.             type = _IONBF;
  148.             break;
  149.         case 1:
  150.             type = _IOLBF;
  151.             bufsize = BUFSIZ;
  152.             break;
  153.         default:
  154.             type = _IOFBF;
  155.         }
  156.         setvbuf(((PyFileObject *)f)->f_fp, (char *)NULL,
  157.             type, bufsize);
  158. #else /* !HAVE_SETVBUF */
  159.         if (bufsize <= 1)
  160.             setbuf(((PyFileObject *)f)->f_fp, (char *)NULL);
  161. #endif /* !HAVE_SETVBUF */
  162.     }
  163. }
  164.  
  165. static PyObject *
  166. err_closed()
  167. {
  168.     PyErr_SetString(PyExc_ValueError, "I/O operation on closed file");
  169.     return NULL;
  170. }
  171.  
  172. /* Methods */
  173.  
  174. static void
  175. file_dealloc(f)
  176.     PyFileObject *f;
  177. {
  178.     if (f->f_fp != NULL && f->f_close != NULL) {
  179.         Py_BEGIN_ALLOW_THREADS
  180.         (*f->f_close)(f->f_fp);
  181.         Py_END_ALLOW_THREADS
  182.     }
  183.     if (f->f_name != NULL) {
  184.         Py_DECREF(f->f_name);
  185.     }
  186.     if (f->f_mode != NULL) {
  187.         Py_DECREF(f->f_mode);
  188.     }
  189.     PyObject_DEL(f);
  190. }
  191.  
  192. static PyObject *
  193. file_repr(f)
  194.     PyFileObject *f;
  195. {
  196.     char buf[300];
  197.     sprintf(buf, "<%s file '%.256s', mode '%.10s' at %lx>",
  198.         f->f_fp == NULL ? "closed" : "open",
  199.         PyString_AsString(f->f_name),
  200.         PyString_AsString(f->f_mode),
  201.         (long)f);
  202.     return PyString_FromString(buf);
  203. }
  204.  
  205. static PyObject *
  206. file_close(f, args)
  207.     PyFileObject *f;
  208.     PyObject *args;
  209. {
  210.     int sts = 0;
  211.     if (!PyArg_NoArgs(args))
  212.         return NULL;
  213.     if (f->f_fp != NULL) {
  214.         if (f->f_close != NULL) {
  215.             Py_BEGIN_ALLOW_THREADS
  216.             errno = 0;
  217.             sts = (*f->f_close)(f->f_fp);
  218.             Py_END_ALLOW_THREADS
  219.         }
  220.         f->f_fp = NULL;
  221.     }
  222.     if (sts == EOF)
  223.         return PyErr_SetFromErrno(PyExc_IOError);
  224.     if (sts != 0)
  225.         return PyInt_FromLong((long)sts);
  226.     Py_INCREF(Py_None);
  227.     return Py_None;
  228. }
  229.  
  230. static PyObject *
  231. file_seek(f, args)
  232.     PyFileObject *f;
  233.     PyObject *args;
  234. {
  235.     int whence;
  236.     int ret;
  237.     off_t offset;
  238.     PyObject *offobj;
  239.     
  240.     if (f->f_fp == NULL)
  241.         return err_closed();
  242.     whence = 0;
  243.     if (!PyArg_ParseTuple(args, "O|i:seek", &offobj, &whence))
  244.         return NULL;
  245. #if !defined(HAVE_LARGEFILE_SUPPORT)
  246.     offset = PyInt_AsLong(offobj);
  247. #else
  248.     offset = PyLong_Check(offobj) ?
  249.         PyLong_AsLongLong(offobj) : PyInt_AsLong(offobj);
  250. #endif
  251.     if (PyErr_Occurred())
  252.         return NULL;
  253.     Py_BEGIN_ALLOW_THREADS
  254.     errno = 0;
  255. #if defined(HAVE_FSEEKO)
  256.     ret = fseeko(f->f_fp, offset, whence);
  257. #elif defined(HAVE_FSEEK64)
  258.     ret = fseek64(f->f_fp, offset, whence);
  259. #else
  260.     ret = fseek(f->f_fp, offset, whence);
  261. #endif
  262.     Py_END_ALLOW_THREADS
  263.     if (ret != 0) {
  264.         PyErr_SetFromErrno(PyExc_IOError);
  265.         clearerr(f->f_fp);
  266.         return NULL;
  267.     }
  268.     Py_INCREF(Py_None);
  269.     return Py_None;
  270. }
  271.  
  272. #ifdef HAVE_FTRUNCATE
  273. static PyObject *
  274. file_truncate(f, args)
  275.     PyFileObject *f;
  276.     PyObject *args;
  277. {
  278.     int ret;
  279.     off_t newsize;
  280.     PyObject *newsizeobj;
  281.     
  282.     if (f->f_fp == NULL)
  283.         return err_closed();
  284.     newsizeobj = NULL;
  285.     if (!PyArg_ParseTuple(args, "|O:truncate", &newsizeobj))
  286.         return NULL;
  287.     if (newsizeobj != NULL) {
  288. #if !defined(HAVE_LARGEFILE_SUPPORT)
  289.         newsize = PyInt_AsLong(newsizeobj);
  290. #else
  291.         newsize = PyLong_Check(newsizeobj) ?
  292.                 PyLong_AsLongLong(newsizeobj) :
  293.                 PyInt_AsLong(newsizeobj);
  294. #endif
  295.         if (PyErr_Occurred())
  296.             return NULL;
  297.     } else {
  298.         /* Default to current position*/
  299.         Py_BEGIN_ALLOW_THREADS
  300.         errno = 0;
  301. #if defined(HAVE_FTELLO) && defined(HAVE_LARGEFILE_SUPPORT)
  302.         newsize =  ftello(f->f_fp);
  303. #elif defined(HAVE_FTELL64) && defined(HAVE_LARGEFILE_SUPPORT)
  304.         newsize =  ftell64(f->f_fp);
  305. #else
  306.         newsize =  ftell(f->f_fp);
  307. #endif
  308.         Py_END_ALLOW_THREADS
  309.         if (newsize == -1) {
  310.                 PyErr_SetFromErrno(PyExc_IOError);
  311.             clearerr(f->f_fp);
  312.             return NULL;
  313.         }
  314.     }
  315.     Py_BEGIN_ALLOW_THREADS
  316.     errno = 0;
  317.     ret = fflush(f->f_fp);
  318.     Py_END_ALLOW_THREADS
  319.     if (ret == 0) {
  320.             Py_BEGIN_ALLOW_THREADS
  321.         errno = 0;
  322.         ret = ftruncate(fileno(f->f_fp), newsize);
  323.         Py_END_ALLOW_THREADS
  324.     }
  325.     if (ret != 0) {
  326.         PyErr_SetFromErrno(PyExc_IOError);
  327.         clearerr(f->f_fp);
  328.         return NULL;
  329.     }
  330.     Py_INCREF(Py_None);
  331.     return Py_None;
  332. }
  333. #endif /* HAVE_FTRUNCATE */
  334.  
  335. static PyObject *
  336. file_tell(f, args)
  337.     PyFileObject *f;
  338.     PyObject *args;
  339. {
  340.     off_t offset;
  341.     if (f->f_fp == NULL)
  342.         return err_closed();
  343.     if (!PyArg_NoArgs(args))
  344.         return NULL;
  345.     Py_BEGIN_ALLOW_THREADS
  346.     errno = 0;
  347. #if defined(HAVE_FTELLO) && defined(HAVE_LARGEFILE_SUPPORT)
  348.     offset = ftello(f->f_fp);
  349. #elif defined(HAVE_FTELL64) && defined(HAVE_LARGEFILE_SUPPORT)
  350.     offset = ftell64(f->f_fp);
  351. #else
  352.     offset = ftell(f->f_fp);
  353. #endif
  354.     Py_END_ALLOW_THREADS
  355.     if (offset == -1) {
  356.         PyErr_SetFromErrno(PyExc_IOError);
  357.         clearerr(f->f_fp);
  358.         return NULL;
  359.     }
  360. #if !defined(HAVE_LARGEFILE_SUPPORT)
  361.     return PyInt_FromLong(offset);
  362. #else
  363.     return PyLong_FromLongLong(offset);
  364. #endif
  365. }
  366.  
  367. static PyObject *
  368. file_fileno(f, args)
  369.     PyFileObject *f;
  370.     PyObject *args;
  371. {
  372.     if (f->f_fp == NULL)
  373.         return err_closed();
  374.     if (!PyArg_NoArgs(args))
  375.         return NULL;
  376.     return PyInt_FromLong((long) fileno(f->f_fp));
  377. }
  378.  
  379. static PyObject *
  380. file_flush(f, args)
  381.     PyFileObject *f;
  382.     PyObject *args;
  383. {
  384.     int res;
  385.     
  386.     if (f->f_fp == NULL)
  387.         return err_closed();
  388.     if (!PyArg_NoArgs(args))
  389.         return NULL;
  390.     Py_BEGIN_ALLOW_THREADS
  391.     errno = 0;
  392.     res = fflush(f->f_fp);
  393.     Py_END_ALLOW_THREADS
  394.     if (res != 0) {
  395.         PyErr_SetFromErrno(PyExc_IOError);
  396.         clearerr(f->f_fp);
  397.         return NULL;
  398.     }
  399.     Py_INCREF(Py_None);
  400.     return Py_None;
  401. }
  402.  
  403. static PyObject *
  404. file_isatty(f, args)
  405.     PyFileObject *f;
  406.     PyObject *args;
  407. {
  408.     long res;
  409.     if (f->f_fp == NULL)
  410.         return err_closed();
  411.     if (!PyArg_NoArgs(args))
  412.         return NULL;
  413.     Py_BEGIN_ALLOW_THREADS
  414.     res = isatty((int)fileno(f->f_fp));
  415.     Py_END_ALLOW_THREADS
  416.     return PyInt_FromLong(res);
  417. }
  418.  
  419. /* We expect that fstat exists on most systems.
  420.    It's confirmed on Unix, Mac and Windows.
  421.    If you don't have it, add #define DONT_HAVE_FSTAT to your config.h. */
  422. #ifndef DONT_HAVE_FSTAT
  423. #define HAVE_FSTAT
  424.  
  425. #ifndef DONT_HAVE_SYS_TYPES_H
  426. #include <sys/types.h>
  427. #endif
  428.  
  429. #ifndef DONT_HAVE_SYS_STAT_H
  430. #include <sys/stat.h>
  431. #endif
  432.  
  433. #endif /* DONT_HAVE_FSTAT */
  434.  
  435. #if BUFSIZ < 8192
  436. #define SMALLCHUNK 8192
  437. #else
  438. #define SMALLCHUNK BUFSIZ
  439. #endif
  440.  
  441. #if SIZEOF_INT < 4
  442. #define BIGCHUNK  (512 * 32)
  443. #else
  444. #define BIGCHUNK  (512 * 1024)
  445. #endif
  446.  
  447. static size_t
  448. new_buffersize(f, currentsize)
  449.     PyFileObject *f;
  450.     size_t currentsize;
  451. {
  452. #ifdef HAVE_FSTAT
  453.     long pos, end;
  454.     struct stat st;
  455.     if (fstat(fileno(f->f_fp), &st) == 0) {
  456.         end = st.st_size;
  457.         /* The following is not a bug: we really need to call lseek()
  458.            *and* ftell().  The reason is that some stdio libraries
  459.            mistakenly flush their buffer when ftell() is called and
  460.            the lseek() call it makes fails, thereby throwing away
  461.            data that cannot be recovered in any way.  To avoid this,
  462.            we first test lseek(), and only call ftell() if lseek()
  463.            works.  We can't use the lseek() value either, because we
  464.            need to take the amount of buffered data into account.
  465.            (Yet another reason why stdio stinks. :-) */
  466.         pos = lseek(fileno(f->f_fp), 0L, SEEK_CUR);
  467.         if (pos >= 0)
  468.             pos = ftell(f->f_fp);
  469.         if (pos < 0)
  470.             clearerr(f->f_fp);
  471.         if (end > pos && pos >= 0)
  472.             return currentsize + end - pos + 1;
  473.         /* Add 1 so if the file were to grow we'd notice. */
  474.     }
  475. #endif
  476.     if (currentsize > SMALLCHUNK) {
  477.         /* Keep doubling until we reach BIGCHUNK;
  478.            then keep adding BIGCHUNK. */
  479.         if (currentsize <= BIGCHUNK)
  480.             return currentsize + currentsize;
  481.         else
  482.             return currentsize + BIGCHUNK;
  483.     }
  484.     return currentsize + SMALLCHUNK;
  485. }
  486.  
  487. static PyObject *
  488. file_read(f, args)
  489.     PyFileObject *f;
  490.     PyObject *args;
  491. {
  492.     long bytesrequested = -1;
  493.     size_t bytesread, buffersize, chunksize;
  494.     PyObject *v;
  495.     
  496.     if (f->f_fp == NULL)
  497.         return err_closed();
  498.     if (!PyArg_ParseTuple(args, "|l:read", &bytesrequested))
  499.         return NULL;
  500.     if (bytesrequested < 0)
  501.         buffersize = new_buffersize(f, (size_t)0);
  502.     else
  503.         buffersize = bytesrequested;
  504.     v = PyString_FromStringAndSize((char *)NULL, buffersize);
  505.     if (v == NULL)
  506.         return NULL;
  507.     bytesread = 0;
  508.     for (;;) {
  509.         Py_BEGIN_ALLOW_THREADS
  510.         errno = 0;
  511.         chunksize = fread(BUF(v) + bytesread, 1,
  512.                   buffersize - bytesread, f->f_fp);
  513.         Py_END_ALLOW_THREADS
  514.         if (chunksize == 0) {
  515.             if (!ferror(f->f_fp))
  516.                 break;
  517.             PyErr_SetFromErrno(PyExc_IOError);
  518.             clearerr(f->f_fp);
  519.             Py_DECREF(v);
  520.             return NULL;
  521.         }
  522.         bytesread += chunksize;
  523.         if (bytesread < buffersize)
  524.             break;
  525.         if (bytesrequested < 0) {
  526.             buffersize = new_buffersize(f, buffersize);
  527.             if (_PyString_Resize(&v, buffersize) < 0)
  528.                 return NULL;
  529.         }
  530.     }
  531.     if (bytesread != buffersize)
  532.         _PyString_Resize(&v, bytesread);
  533.     return v;
  534. }
  535.  
  536. static PyObject *
  537. file_readinto(f, args)
  538.     PyFileObject *f;
  539.     PyObject *args;
  540. {
  541.     char *ptr;
  542.     int ntodo, ndone, nnow;
  543.     
  544.     if (f->f_fp == NULL)
  545.         return err_closed();
  546.     if (!PyArg_Parse(args, "w#", &ptr, &ntodo))
  547.         return NULL;
  548.     ndone = 0;
  549.     while (ntodo > 0) {
  550.         Py_BEGIN_ALLOW_THREADS
  551.         errno = 0;
  552.         nnow = fread(ptr+ndone, 1, ntodo, f->f_fp);
  553.         Py_END_ALLOW_THREADS
  554.         if (nnow == 0) {
  555.             if (!ferror(f->f_fp))
  556.                 break;
  557.             PyErr_SetFromErrno(PyExc_IOError);
  558.             clearerr(f->f_fp);
  559.             return NULL;
  560.         }
  561.         ndone += nnow;
  562.         ntodo -= nnow;
  563.     }
  564.     return PyInt_FromLong(ndone);
  565. }
  566.  
  567.  
  568. /* Internal routine to get a line.
  569.    Size argument interpretation:
  570.    > 0: max length;
  571.    = 0: read arbitrary line;
  572.    < 0: strip trailing '\n', raise EOFError if EOF reached immediately
  573. */
  574.  
  575. static PyObject *
  576. get_line(f, n)
  577.     PyFileObject *f;
  578.     int n;
  579. {
  580.     register FILE *fp;
  581.     register int c;
  582.     register char *buf, *end;
  583.     int n1, n2;
  584.     PyObject *v;
  585.  
  586.     fp = f->f_fp;
  587.     n2 = n > 0 ? n : 100;
  588.     v = PyString_FromStringAndSize((char *)NULL, n2);
  589.     if (v == NULL)
  590.         return NULL;
  591.     buf = BUF(v);
  592.     end = buf + n2;
  593.  
  594.     Py_BEGIN_ALLOW_THREADS
  595.     for (;;) {
  596.         if ((c = getc(fp)) == EOF) {
  597.             clearerr(fp);
  598.             Py_BLOCK_THREADS
  599.             if (PyErr_CheckSignals()) {
  600.                 Py_DECREF(v);
  601.                 return NULL;
  602.             }
  603.             if (n < 0 && buf == BUF(v)) {
  604.                 Py_DECREF(v);
  605.                 PyErr_SetString(PyExc_EOFError,
  606.                        "EOF when reading a line");
  607.                 return NULL;
  608.             }
  609.             Py_UNBLOCK_THREADS
  610.             break;
  611.         }
  612.         if ((*buf++ = c) == '\n') {
  613.             if (n < 0)
  614.                 buf--;
  615.             break;
  616.         }
  617.         if (buf == end) {
  618.             if (n > 0)
  619.                 break;
  620.             n1 = n2;
  621.             n2 += 1000;
  622.             Py_BLOCK_THREADS
  623.             if (_PyString_Resize(&v, n2) < 0)
  624.                 return NULL;
  625.             Py_UNBLOCK_THREADS
  626.             buf = BUF(v) + n1;
  627.             end = BUF(v) + n2;
  628.         }
  629.     }
  630.     Py_END_ALLOW_THREADS
  631.  
  632.     n1 = buf - BUF(v);
  633.     if (n1 != n2)
  634.         _PyString_Resize(&v, n1);
  635.     return v;
  636. }
  637.  
  638. /* External C interface */
  639.  
  640. PyObject *
  641. PyFile_GetLine(f, n)
  642.     PyObject *f;
  643.     int n;
  644. {
  645.     if (f == NULL) {
  646.         PyErr_BadInternalCall();
  647.         return NULL;
  648.     }
  649.     if (!PyFile_Check(f)) {
  650.         PyObject *reader;
  651.         PyObject *args;
  652.         PyObject *result;
  653.         reader = PyObject_GetAttrString(f, "readline");
  654.         if (reader == NULL)
  655.             return NULL;
  656.         if (n <= 0)
  657.             args = Py_BuildValue("()");
  658.         else
  659.             args = Py_BuildValue("(i)", n);
  660.         if (args == NULL) {
  661.             Py_DECREF(reader);
  662.             return NULL;
  663.         }
  664.         result = PyEval_CallObject(reader, args);
  665.         Py_DECREF(reader);
  666.         Py_DECREF(args);
  667.         if (result != NULL && !PyString_Check(result)) {
  668.             Py_DECREF(result);
  669.             result = NULL;
  670.             PyErr_SetString(PyExc_TypeError,
  671.                    "object.readline() returned non-string");
  672.         }
  673.         if (n < 0 && result != NULL) {
  674.             char *s = PyString_AsString(result);
  675.             int len = PyString_Size(result);
  676.             if (len == 0) {
  677.                 Py_DECREF(result);
  678.                 result = NULL;
  679.                 PyErr_SetString(PyExc_EOFError,
  680.                        "EOF when reading a line");
  681.             }
  682.             else if (s[len-1] == '\n') {
  683.                 if (result->ob_refcnt == 1)
  684.                     _PyString_Resize(&result, len-1);
  685.                 else {
  686.                     PyObject *v;
  687.                     v = PyString_FromStringAndSize(s,
  688.                                        len-1);
  689.                     Py_DECREF(result);
  690.                     result = v;
  691.                 }
  692.             }
  693.         }
  694.         return result;
  695.     }
  696.     if (((PyFileObject*)f)->f_fp == NULL)
  697.         return err_closed();
  698.     return get_line((PyFileObject *)f, n);
  699. }
  700.  
  701. /* Python method */
  702.  
  703. static PyObject *
  704. file_readline(f, args)
  705.     PyFileObject *f;
  706.     PyObject *args;
  707. {
  708.     int n = -1;
  709.  
  710.     if (f->f_fp == NULL)
  711.         return err_closed();
  712.     if (!PyArg_ParseTuple(args, "|i:readline", &n))
  713.         return NULL;
  714.     if (n == 0)
  715.         return PyString_FromString("");
  716.     if (n < 0)
  717.         n = 0;
  718.     return get_line(f, n);
  719. }
  720.  
  721. static PyObject *
  722. file_readlines(f, args)
  723.     PyFileObject *f;
  724.     PyObject *args;
  725. {
  726.     long sizehint = 0;
  727.     PyObject *list;
  728.     PyObject *line;
  729.     char small_buffer[SMALLCHUNK];
  730.     char *buffer = small_buffer;
  731.     size_t buffersize = SMALLCHUNK;
  732.     PyObject *big_buffer = NULL;
  733.     size_t nfilled = 0;
  734.     size_t nread;
  735.     size_t totalread = 0;
  736.     char *p, *q, *end;
  737.     int err;
  738.  
  739.     if (f->f_fp == NULL)
  740.         return err_closed();
  741.     if (!PyArg_ParseTuple(args, "|l:readlines", &sizehint))
  742.         return NULL;
  743.     if ((list = PyList_New(0)) == NULL)
  744.         return NULL;
  745.     for (;;) {
  746.         Py_BEGIN_ALLOW_THREADS
  747.         errno = 0;
  748.         nread = fread(buffer+nfilled, 1, buffersize-nfilled, f->f_fp);
  749.         Py_END_ALLOW_THREADS
  750.         if (nread == 0) {
  751.             sizehint = 0;
  752.             if (!ferror(f->f_fp))
  753.                 break;
  754.             PyErr_SetFromErrno(PyExc_IOError);
  755.             clearerr(f->f_fp);
  756.           error:
  757.             Py_DECREF(list);
  758.             list = NULL;
  759.             goto cleanup;
  760.         }
  761.         totalread += nread;
  762.         p = memchr(buffer+nfilled, '\n', nread);
  763.         if (p == NULL) {
  764.             /* Need a larger buffer to fit this line */
  765.             nfilled += nread;
  766.             buffersize *= 2;
  767.             if (big_buffer == NULL) {
  768.                 /* Create the big buffer */
  769.                 big_buffer = PyString_FromStringAndSize(
  770.                     NULL, buffersize);
  771.                 if (big_buffer == NULL)
  772.                     goto error;
  773.                 buffer = PyString_AS_STRING(big_buffer);
  774.                 memcpy(buffer, small_buffer, nfilled);
  775.             }
  776.             else {
  777.                 /* Grow the big buffer */
  778.                 _PyString_Resize(&big_buffer, buffersize);
  779.                 buffer = PyString_AS_STRING(big_buffer);
  780.             }
  781.             continue;
  782.         }
  783.         end = buffer+nfilled+nread;
  784.         q = buffer;
  785.         do {
  786.             /* Process complete lines */
  787.             p++;
  788.             line = PyString_FromStringAndSize(q, p-q);
  789.             if (line == NULL)
  790.                 goto error;
  791.             err = PyList_Append(list, line);
  792.             Py_DECREF(line);
  793.             if (err != 0)
  794.                 goto error;
  795.             q = p;
  796.             p = memchr(q, '\n', end-q);
  797.         } while (p != NULL);
  798.         /* Move the remaining incomplete line to the start */
  799.         nfilled = end-q;
  800.         memmove(buffer, q, nfilled);
  801.         if (sizehint > 0)
  802.             if (totalread >= (size_t)sizehint)
  803.                 break;
  804.     }
  805.     if (nfilled != 0) {
  806.         /* Partial last line */
  807.         line = PyString_FromStringAndSize(buffer, nfilled);
  808.         if (line == NULL)
  809.             goto error;
  810.         if (sizehint > 0) {
  811.             /* Need to complete the last line */
  812.             PyObject *rest = get_line(f, 0);
  813.             if (rest == NULL) {
  814.                 Py_DECREF(line);
  815.                 goto error;
  816.             }
  817.             PyString_Concat(&line, rest);
  818.             Py_DECREF(rest);
  819.             if (line == NULL)
  820.                 goto error;
  821.         }
  822.         err = PyList_Append(list, line);
  823.         Py_DECREF(line);
  824.         if (err != 0)
  825.             goto error;
  826.     }
  827.   cleanup:
  828.     if (big_buffer) {
  829.         Py_DECREF(big_buffer);
  830.     }
  831.     return list;
  832. }
  833.  
  834. static PyObject *
  835. file_write(f, args)
  836.     PyFileObject *f;
  837.     PyObject *args;
  838. {
  839.     char *s;
  840.     int n, n2;
  841.     if (f->f_fp == NULL)
  842.         return err_closed();
  843.     if (!PyArg_Parse(args, f->f_binary ? "s#" : "t#", &s, &n))
  844.         return NULL;
  845.     f->f_softspace = 0;
  846.     Py_BEGIN_ALLOW_THREADS
  847.     errno = 0;
  848.     n2 = fwrite(s, 1, n, f->f_fp);
  849.     Py_END_ALLOW_THREADS
  850.     if (n2 != n) {
  851.         PyErr_SetFromErrno(PyExc_IOError);
  852.         clearerr(f->f_fp);
  853.         return NULL;
  854.     }
  855.     Py_INCREF(Py_None);
  856.     return Py_None;
  857. }
  858.  
  859. static PyObject *
  860. file_writelines(f, args)
  861.     PyFileObject *f;
  862.     PyObject *args;
  863. {
  864. #define CHUNKSIZE 1000
  865.     PyObject *list, *line;
  866.     PyObject *result;
  867.     int i, j, index, len, nwritten, islist;
  868.  
  869.     if (f->f_fp == NULL)
  870.         return err_closed();
  871.     if (args == NULL || !PySequence_Check(args)) {
  872.         PyErr_SetString(PyExc_TypeError,
  873.                "writelines() requires sequence of strings");
  874.         return NULL;
  875.     }
  876.     islist = PyList_Check(args);
  877.  
  878.     /* Strategy: slurp CHUNKSIZE lines into a private list,
  879.        checking that they are all strings, then write that list
  880.        without holding the interpreter lock, then come back for more. */
  881.     index = 0;
  882.     if (islist)
  883.         list = NULL;
  884.     else {
  885.         list = PyList_New(CHUNKSIZE);
  886.         if (list == NULL)
  887.             return NULL;
  888.     }
  889.     result = NULL;
  890.  
  891.     for (;;) {
  892.         if (islist) {
  893.             Py_XDECREF(list);
  894.             list = PyList_GetSlice(args, index, index+CHUNKSIZE);
  895.             if (list == NULL)
  896.                 return NULL;
  897.             j = PyList_GET_SIZE(list);
  898.         }
  899.         else {
  900.             for (j = 0; j < CHUNKSIZE; j++) {
  901.                 line = PySequence_GetItem(args, index+j);
  902.                 if (line == NULL) {
  903.                     if (PyErr_ExceptionMatches(
  904.                         PyExc_IndexError)) {
  905.                         PyErr_Clear();
  906.                         break;
  907.                     }
  908.                     /* Some other error occurred.
  909.                        XXX We may lose some output. */
  910.                     goto error;
  911.                 }
  912.                 PyList_SetItem(list, j, line);
  913.             }
  914.         }
  915.         if (j == 0)
  916.             break;
  917.  
  918.         /* Check that all entries are indeed strings. If not,
  919.            apply the same rules as for file.write() and
  920.            convert the results to strings. This is slow, but
  921.            seems to be the only way since all conversion APIs
  922.            could potentially execute Python code. */
  923.         for (i = 0; i < j; i++) {
  924.             PyObject *v = PyList_GET_ITEM(list, i);
  925.             if (!PyString_Check(v)) {
  926.                     const char *buffer;
  927.                     int len;
  928.                 if (((f->f_binary && 
  929.                       PyObject_AsReadBuffer(v,
  930.                           (const void**)&buffer,
  931.                                 &len)) ||
  932.                      PyObject_AsCharBuffer(v,
  933.                                &buffer,
  934.                                &len))) {
  935.                     PyErr_SetString(PyExc_TypeError,
  936.                 "writelines() requires sequences of strings");
  937.                     goto error;
  938.                 }
  939.                 line = PyString_FromStringAndSize(buffer,
  940.                                   len);
  941.                 if (line == NULL)
  942.                     goto error;
  943.                 Py_DECREF(v);
  944.                 PyList_SET_ITEM(list, i, line);
  945.             }
  946.         }
  947.  
  948.         /* Since we are releasing the global lock, the
  949.            following code may *not* execute Python code. */
  950.         Py_BEGIN_ALLOW_THREADS
  951.         f->f_softspace = 0;
  952.         errno = 0;
  953.         for (i = 0; i < j; i++) {
  954.                 line = PyList_GET_ITEM(list, i);
  955.             len = PyString_GET_SIZE(line);
  956.             nwritten = fwrite(PyString_AS_STRING(line),
  957.                       1, len, f->f_fp);
  958.             if (nwritten != len) {
  959.                 Py_BLOCK_THREADS
  960.                 PyErr_SetFromErrno(PyExc_IOError);
  961.                 clearerr(f->f_fp);
  962.                 goto error;
  963.             }
  964.         }
  965.         Py_END_ALLOW_THREADS
  966.  
  967.         if (j < CHUNKSIZE)
  968.             break;
  969.         index += CHUNKSIZE;
  970.     }
  971.  
  972.     Py_INCREF(Py_None);
  973.     result = Py_None;
  974.   error:
  975.     Py_XDECREF(list);
  976.     return result;
  977. }
  978.  
  979. static PyMethodDef file_methods[] = {
  980.     {"readline",    (PyCFunction)file_readline, 1},
  981.     {"read",    (PyCFunction)file_read, 1},
  982.     {"write",    (PyCFunction)file_write, 0},
  983.     {"fileno",    (PyCFunction)file_fileno, 0},
  984.     {"seek",    (PyCFunction)file_seek, 1},
  985. #ifdef HAVE_FTRUNCATE
  986.     {"truncate",    (PyCFunction)file_truncate, 1},
  987. #endif
  988.     {"tell",    (PyCFunction)file_tell, 0},
  989.     {"readinto",    (PyCFunction)file_readinto, 0},
  990.     {"readlines",    (PyCFunction)file_readlines, 1},
  991.     {"writelines",    (PyCFunction)file_writelines, 0},
  992.     {"flush",    (PyCFunction)file_flush, 0},
  993.     {"close",    (PyCFunction)file_close, 0},
  994.     {"isatty",    (PyCFunction)file_isatty, 0},
  995.     {NULL,        NULL}        /* sentinel */
  996. };
  997.  
  998. #define OFF(x) offsetof(PyFileObject, x)
  999.  
  1000. static struct memberlist file_memberlist[] = {
  1001.     {"softspace",    T_INT,        OFF(f_softspace)},
  1002.     {"mode",    T_OBJECT,    OFF(f_mode),    RO},
  1003.     {"name",    T_OBJECT,    OFF(f_name),    RO},
  1004.     /* getattr(f, "closed") is implemented without this table */
  1005.     {"closed",    T_INT,        0,        RO},
  1006.     {NULL}    /* Sentinel */
  1007. };
  1008.  
  1009. static PyObject *
  1010. file_getattr(f, name)
  1011.     PyFileObject *f;
  1012.     char *name;
  1013. {
  1014.     PyObject *res;
  1015.  
  1016.     res = Py_FindMethod(file_methods, (PyObject *)f, name);
  1017.     if (res != NULL)
  1018.         return res;
  1019.     PyErr_Clear();
  1020.     if (strcmp(name, "closed") == 0)
  1021.         return PyInt_FromLong((long)(f->f_fp == 0));
  1022.     return PyMember_Get((char *)f, file_memberlist, name);
  1023. }
  1024.  
  1025. static int
  1026. file_setattr(f, name, v)
  1027.     PyFileObject *f;
  1028.     char *name;
  1029.     PyObject *v;
  1030. {
  1031.     if (v == NULL) {
  1032.         PyErr_SetString(PyExc_AttributeError,
  1033.                 "can't delete file attributes");
  1034.         return -1;
  1035.     }
  1036.     return PyMember_Set((char *)f, file_memberlist, name, v);
  1037. }
  1038.  
  1039. PyTypeObject PyFile_Type = {
  1040.     PyObject_HEAD_INIT(&PyType_Type)
  1041.     0,
  1042.     "file",
  1043.     sizeof(PyFileObject),
  1044.     0,
  1045.     (destructor)file_dealloc, /*tp_dealloc*/
  1046.     0,        /*tp_print*/
  1047.     (getattrfunc)file_getattr, /*tp_getattr*/
  1048.     (setattrfunc)file_setattr, /*tp_setattr*/
  1049.     0,        /*tp_compare*/
  1050.     (reprfunc)file_repr, /*tp_repr*/
  1051. };
  1052.  
  1053. /* Interface for the 'soft space' between print items. */
  1054.  
  1055. int
  1056. PyFile_SoftSpace(f, newflag)
  1057.     PyObject *f;
  1058.     int newflag;
  1059. {
  1060.     int oldflag = 0;
  1061.     if (f == NULL) {
  1062.         /* Do nothing */
  1063.     }
  1064.     else if (PyFile_Check(f)) {
  1065.         oldflag = ((PyFileObject *)f)->f_softspace;
  1066.         ((PyFileObject *)f)->f_softspace = newflag;
  1067.     }
  1068.     else {
  1069.         PyObject *v;
  1070.         v = PyObject_GetAttrString(f, "softspace");
  1071.         if (v == NULL)
  1072.             PyErr_Clear();
  1073.         else {
  1074.             if (PyInt_Check(v))
  1075.                 oldflag = PyInt_AsLong(v);
  1076.             Py_DECREF(v);
  1077.         }
  1078.         v = PyInt_FromLong((long)newflag);
  1079.         if (v == NULL)
  1080.             PyErr_Clear();
  1081.         else {
  1082.             if (PyObject_SetAttrString(f, "softspace", v) != 0)
  1083.                 PyErr_Clear();
  1084.             Py_DECREF(v);
  1085.         }
  1086.     }
  1087.     return oldflag;
  1088. }
  1089.  
  1090. /* Interfaces to write objects/strings to file-like objects */
  1091.  
  1092. int
  1093. PyFile_WriteObject(v, f, flags)
  1094.     PyObject *v;
  1095.     PyObject *f;
  1096.     int flags;
  1097. {
  1098.     PyObject *writer, *value, *args, *result;
  1099.     if (f == NULL) {
  1100.         PyErr_SetString(PyExc_TypeError, "writeobject with NULL file");
  1101.         return -1;
  1102.     }
  1103.     else if (PyFile_Check(f)) {
  1104.         FILE *fp = PyFile_AsFile(f);
  1105.         if (fp == NULL) {
  1106.             err_closed();
  1107.             return -1;
  1108.         }
  1109.         return PyObject_Print(v, fp, flags);
  1110.     }
  1111.     writer = PyObject_GetAttrString(f, "write");
  1112.     if (writer == NULL)
  1113.         return -1;
  1114.     if (flags & Py_PRINT_RAW)
  1115.         value = PyObject_Str(v);
  1116.     else
  1117.         value = PyObject_Repr(v);
  1118.     if (value == NULL) {
  1119.         Py_DECREF(writer);
  1120.         return -1;
  1121.     }
  1122.     args = Py_BuildValue("(O)", value);
  1123.     if (args == NULL) {
  1124.         Py_DECREF(value);
  1125.         Py_DECREF(writer);
  1126.         return -1;
  1127.     }
  1128.     result = PyEval_CallObject(writer, args);
  1129.     Py_DECREF(args);
  1130.     Py_DECREF(value);
  1131.     Py_DECREF(writer);
  1132.     if (result == NULL)
  1133.         return -1;
  1134.     Py_DECREF(result);
  1135.     return 0;
  1136. }
  1137.  
  1138. int
  1139. PyFile_WriteString(s, f)
  1140.     char *s;
  1141.     PyObject *f;
  1142. {
  1143.     if (f == NULL) {
  1144.         /* Should be caused by a pre-existing error */
  1145.         if(!PyErr_Occurred())
  1146.             PyErr_SetString(PyExc_SystemError,
  1147.                     "null file for PyFile_WriteString");
  1148.         return -1;
  1149.     }
  1150.     else if (PyFile_Check(f)) {
  1151.         FILE *fp = PyFile_AsFile(f);
  1152.         if (fp == NULL) {
  1153.             err_closed();
  1154.             return -1;
  1155.         }
  1156.         fputs(s, fp);
  1157.         return 0;
  1158.     }
  1159.     else if (!PyErr_Occurred()) {
  1160.         PyObject *v = PyString_FromString(s);
  1161.         int err;
  1162.         if (v == NULL)
  1163.             return -1;
  1164.         err = PyFile_WriteObject(v, f, Py_PRINT_RAW);
  1165.         Py_DECREF(v);
  1166.         return err;
  1167.     }
  1168.     else
  1169.         return -1;
  1170. }
  1171.